import React, { memo, useEffect, useMemo, useState } from 'react';

import { Button, Card, Form, Input, message, Spin, Tooltip, TreeSelect, Checkbox, Radio } from 'antd';
import { history } from 'umi'

import { BottomAction } from '@/components';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import OrganizationSelect from '@/components/OrganizationSelect';
import pageTabUtil from '@/utils/pageTabUtil';
import { defaultFormatResult, useRequest } from '@/hooks';
import { getDutyListByOrganizationV2 } from '@/pages/TurnoverSetting/EntrySetting/services';
import { array2Tree } from '@/utils/tree';
import { Icon } from '@/pages/Recruitment/components';
import cn from 'classnames';
import HandoverTable from '../components/HandoverTable';
import styles from './index.less';
import { DATE_UNIT, SALARY_SELECT, SALARY_TIME } from './enum';
import { generateTreeNodes, getItem, getShowName } from './utils';
import { getHandoverFlowDetail, getHandoverFlowInitialDetail, handleAddHandoverFlow, handleSaveHandoverFlow } from '../services';

/**
 * 交接流程配置-新增/编辑/详情
 */
const HandoverFlowSettingEdit = ({ form, location }) => {
    const { query, pathname } = location;
    const { id } = query;
    const currentUser = JSON.parse(localStorage.getItem('user') || {});
    const { administrativeOrganizationCode } = currentUser || {};

    const type = useMemo(() => {
        if (pathname.toLowerCase().includes('detail')) return 'detail';
        return id ? 'edit' : 'create';
    }, [id]);

    const isForm = type !== 'detail';

    const title = useMemo(() => {
        if (pathname.toLowerCase().includes('detail')) return '交接流程配置详情';
        return id ? '编辑交接流程配置' : '添加交接流程配置';
    }, [id]);

    const [handoverFlowDataSource, setHandoverFlowDataSource] = useState([]);

    const [submitLoading, setSubmitLoading] = useState(false);

    // 创建数据时, 获取默认配置
    const { data: defaultFlowData, loading: defaultDataLoading } = useRequest(getHandoverFlowInitialDetail, {
        ready: type === 'create',
        refreshDeps: [type],
        ...defaultFormatResult
    });

    // 详情/编辑时获取详情
    const { data, loading } = useRequest(() => getHandoverFlowDetail(id, type === 'detail' ? 'view' : 'edit'), {
        ready: !!id,
        refreshDeps: [type],
        ...defaultFormatResult
    });

    // 获取处理人的数据
    const administrativeScope =
        form.getFieldValue('companyCode') ||
        (data?.isDefault === 1 && data.companyCode) ||
        administrativeOrganizationCode;

    const { data: dealDutyData, loading: dealDutyLoading } = useRequest(
        () => getDutyListByOrganizationV2({ organizationCode: administrativeScope, showTreeFlag: 0 }),
        {
            ready: !!administrativeScope,
            refreshDeps: [administrativeScope],
            formatResult: res => {
                // 数据转换
                const filterDuties = tree =>
                    tree.map(i => ({
                        title: i.dutyAlias,
                        value: i.dutyCode,
                        key: i.dutyCode,
                        selectable: i.disable === 0
                    }));
                const filterEnableChildren = item => {
                    let result = false;
                    if (item.children.length) {
                        for (let i = 0; i < item.children.length; i += 1) {
                            if (filterEnableChildren(item.children[i])) {
                                result = true;
                            }
                        }
                    } else {
                        result = item.duties.some(duty => duty.disable === 0);
                    }
                    return result;
                };

                const filterTree = tree =>
                    tree
                        .map(({ children, organizationName, organizationCode, duties, ...props }) => {
                            if (
                                children?.filter(filterEnableChildren).length > 0 ||
                                duties?.filter(item => item.disable === 0).length > 0
                            ) {
                                return {
                                    children: [...filterTree(children), ...filterDuties(duties)],
                                    title: organizationName,
                                    value: organizationCode,
                                    key: organizationCode,
                                    selectable: false,
                                    ...props
                                };
                            }
                            return false;
                        })
                        .filter(Boolean);

                if (res) {
                    const { code, msg } = res;
                    if (code === 10000) {
                        const newData = array2Tree(
                            res.data
                            // .filter(item => item?.duties?.some(duty => duty.disable === 0))
                                .map(item => ({ ...item, duties: item.duties.filter(duty => duty.disable === 0) })),
                            'organizationPath',
                            'parentOrganizationPath'
                        );
                        return filterTree(newData);
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );

    const handleAdministrativeScopeChange = () => {
        const dataSource = handoverFlowDataSource.map(item => {
            if (!item.editFlag) return item;
            return {
                ...item,
                dutyCodeList: [],
                dutyNameList: []
            }
        });
        // 清空form中绑定的数据
        const formValue = {};
        dataSource.forEach(item => {
            formValue[`assignCode-${item.id}`] = []
        });
        form.setFieldsValue({ ...formValue, notifyDutyCodeList: [] });
        // 重置配置内容表格数据
        setHandoverFlowDataSource(dataSource);
    };

    const handleFlowDataSource = (value, label, index) => {
        const dataSource = JSON.parse(JSON.stringify(handoverFlowDataSource));
        dataSource[index] = {
            ...dataSource[index],
            dutyCodeList: value,
            dutyNameList: label
        };
        setHandoverFlowDataSource(dataSource);
    };

    // TODO 若处理人/关键人选择需要限制选择个数，将此处开启即可
    // const getValueFromEvent = args => args.slice(0, 5);

    // 配置内容列配置
    const columns = useMemo(() => {
        const columnList = [
            {
                title: '流程顺序',
                width: '120px',
                render: (text, record, index) => index + 1
            },
            {
                title: '流程名称',
                dataIndex: 'processName'
            },
            {
                title: '处理人',
                dataIndex: 'assignCode',
                width: '250px',
                render: (text, record, index) => {
                    const { editFlag, dutyCodeList, dutyNameList = [] } = record;
                    return <>
                        {!editFlag && type !== 'detail' && <Tooltip title="默认处理人, 不可修改">{dutyNameList?.join('、')}</Tooltip>}
                        {type === 'detail' && dutyNameList?.join('、')}
                        {editFlag && type !== 'detail' && <Form.Item className={styles.assignWrap}>
                            {
                                form.getFieldDecorator(`assignCode-${record.id}`, {
                                    initialValue: dutyCodeList || undefined,
                                    rules: [
                                        {
                                            required: true,
                                            message: '处理人不能为空'
                                        }
                                    ]
                                    // getValueFromEvent
                                })(
                                    <TreeSelect
                                        showArrow
                                        allowClear
                                        showSearch
                                        multiple
                                        placeholder="请选择"
                                        dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                        treeDefaultExpandAll
                                        treeNodeFilterProp="title"
                                        dropdownClassName={styles.treeItemHasDisabledStyle}
                                        onChange={(value, label) => {
                                            // eslint-disable-next-line max-len
                                            // handleFlowDataSource(getValueFromEvent(value), getValueFromEvent(label), index);
                                            handleFlowDataSource(value, label, index);
                                        }}
                                    >
                                        {generateTreeNodes(dealDutyData || [])}
                                    </TreeSelect>
                                )
                            }
                        </Form.Item>}
                    </>
                }
            }
        ];
        if (isForm) {
            columnList.push({
                title: '操作',
                width: '80px',
                render: (text, record) =>
                    record.editFlag ? (
                        <i className={cn('iconfont iconlistfunction_drag_icon_default')} style={{ cursor: 'move' }} />
                    ) : '--'
            });
        }
        return columnList;
    }, [dealDutyData, handoverFlowDataSource]);


    const getContainSalaryFlagdefault = () => {
        if (data?.containSalaryFlag || data?.containSalaryFlag === 0) {
            return data?.containSalaryFlag
        }
        if (defaultFlowData?.containSalaryFlag || defaultFlowData?.containSalaryFlag === 0) {
            return defaultFlowData?.containSalaryFlag;
        }
        return 1;
    };

    const personnelContent = useMemo(
        () => [
            {
                label: '剩余假期结算',
                id: 1,
                disabled: true,
                initialValue: true,
                key: 'remainingTime'
            },
            {
                label: '打印离职证明',
                id: 2,
                disabled: true,
                initialValue: true,
                key: 'printProve'
            },
            {
                detailLabel: `公积金/社保停缴(${DATE_UNIT.find(v => v.key === data?.stopPaymentPfsiType)?.label})`,
                label: (
                    <div style={{ display: 'flex', alignItems: 'center', flewWrap: 'nowrap' }}>
                        <span style={{ marginRight: 8 }}>公积金/社保停缴</span>
                        {form.getFieldDecorator('stopPaymentPfsiType', {
                            initialValue: data?.stopPaymentPfsiType || defaultFlowData?.stopPaymentPfsiType || 1
                        })(
                            <Radio.Group disabled={!form.getFieldValue('personnel.accumulation')}>
                                {DATE_UNIT.map(unit => (
                                    <Radio value={unit.key} key={unit.key}>
                                        {unit.label}
                                    </Radio>
                                ))}
                            </Radio.Group>
                        )}
                    </div>
                ),
                id: 3,
                key: 'accumulation'
            },
            {
                detailLabel: '薪资结算结果',
                label: (
                    <div style={{ display: 'flex', alignItems: 'center', flewWrap: 'nowrap' }}>
                        <span style={{ marginRight: 4 }}>薪资结算结果</span>
                        <Icon
                            type="info-circle"
                            title="选择此内容后，在离职日期当天将自动计算薪资并作为交接任务处理"
                            isAntdIcon
                            size={16}
                        />
                    </div>
                ),
                id: 4,
                key: 'salaryResult'
            },
            {
                label: '回收准证(针对外籍员工)',
                id: 5,
                key: 'recycle'
            }
        ],
        [form, data, defaultFlowData]
    );
    const financeContent = useMemo(
        () => [
            {
                label: '未处理的财务单据',
                id: 1,
                key: 'unDealBills',
                disabled: true,
                initialValue: true
            },
            {
                detailLabel: `财务清算结果(${SALARY_SELECT.find(v => v.key === data?.containSalaryFlag)?.label})`,
                label: (
                    <div style={{ display: 'flex', alignItems: 'center', flewWrap: 'nowrap' }}>
                        <div style={{ lineHeight: 1, display: 'flex', alignItems: 'center', flewWrap: 'nowrap' }}>
                            <span>财务清算结果</span>
                            <div style={{ margin: '0 8px' }}>
                                <Icon
                                    type="info-circle"
                                    title="若包含薪资，在离职日期当天将自动计算薪资作为交接任务处理"
                                    isAntdIcon
                                    size={16}
                                />
                            </div>
                            <span>：</span>
                        </div>
                        <div style={{ marginLeft: 8 }}>
                            {form.getFieldDecorator('containSalaryFlag', {
                                initialValue: getContainSalaryFlagdefault()
                            })(
                                <Radio.Group disabled={!form.getFieldValue('finance.financeResult')}>
                                    {SALARY_SELECT.map(unit => (
                                        <Radio value={unit.key} key={unit.key}>
                                            {unit.label}
                                        </Radio>
                                    ))}
                                </Radio.Group>
                            )}
                        </div>
                    </div>
                ),
                id: 2,
                key: 'financeResult',
                disabled: true,
                initialValue: true
            },
            {
                label: '资产回收情况（资产入库、维修单据、赔偿单据）',
                id: 3,
                key: 'recycleResult'
            }
        ],
        [form, data, defaultFlowData]
    );
    const handleSubmit = action => {
        form.validateFields(async(errors, values) => {
            // console.log(errors, values);
            if (!errors) {
                const {
                    configName,
                    companyCode,
                    notifyDutyCodeList,
                    finance,
                    personnel,
                    stopPaymentPfsiType,
                    containSalaryFlag,
                    allowChoiceSalarySettlementTimeFlag
                } = values;
                const params = {
                    configName,
                    companyCode,
                    processSeqList: handoverFlowDataSource.map((item, index) =>
                        ({ ...item, processSeq: index + 1 })), // 重新计算排序字段
                    notifyDutyCodeList,
                    hrHandoverTypes: personnelContent.map(item => {
                        if (personnel[item.key]) return item.id;
                        return ''
                    }).filter(v => !!v), // 转换为服务端需要的字段
                    financialSettlementType: financeContent.map(item => {
                        if (finance[item.key]) return item.id;
                        return ''
                    }).filter(v => !!v),
                    stopPaymentPfsiType,
                    containSalaryFlag,
                    allowChoiceSalarySettlementTimeFlag: allowChoiceSalarySettlementTimeFlag || 2
                };
                if (id) {
                    params.id = id;
                }
                setSubmitLoading(true);
                try {
                    const queryServices = {
                        create: handleAddHandoverFlow,
                        edit: handleAddHandoverFlow,
                        save: handleSaveHandoverFlow // 预留保存功能接口，目前未启用
                    };
                    const { code, msg } = await queryServices[action](params);
                    if (code === 10000) {
                        message.success('操作成功');
                        pageTabUtil.goBack();
                    } else {
                        message.error(msg);
                    }
                    setSubmitLoading(false);
                } catch (e) {
                    console.log(e)
                }
                console.log('上传的数据', params);
            }
        });
    };
    const handleDefaultData = defaultData => {
        const { hrHandoverTypes = [], financialSettlementType = [] } = defaultData || {};
        const personnel = {};
        const finance = {};
        personnelContent.forEach(item => {
            personnel[item.key] = hrHandoverTypes.includes(item.id)
        });
        financeContent.forEach(item => {
            finance[item.key] = financialSettlementType.includes(item.id)
        });
        // console.log(personnel, finance, '===========');
        form.setFieldsValue({ personnel, finance })
    };
    // 初始化流程表格项
    useEffect(() => {
        if (type === 'create' && defaultFlowData) {
            handleDefaultData(defaultFlowData);
            setHandoverFlowDataSource(defaultFlowData?.processSeqList || []);
        }
    }, [type, defaultFlowData]);
    useEffect(() => {
        if (['edit', 'detail'].includes(type) && data) {
            setHandoverFlowDataSource(data?.processSeqList || []);
        }
        if (data) {
            handleDefaultData(data)
        }
    }, [type, data]);
    return (
        <PageHeaderWrapper>
            <Card
                title={title}
                bordered={false}
                loading={loading || defaultDataLoading}
                extra={
                   !isForm && <Button
                       type="primary"
                       onClick={() => {
                            history.push({
                                pathname: '/office/personnelManagement/onboardAndLeave/setting/leaveSetting/handoverFlow/edit',
                                query: { id: query?.id }
                            });
                        }}
                    >
                       编辑
                   </Button>
                }
            >
                {
                    isForm && <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()} loading={submitLoading}>取消</Button>
                        <Button type="primary" onClick={() => handleSubmit(type)} loading={submitLoading}>
                            确定
                        </Button>
                    </BottomAction>
                }
                <Spin spinning={defaultDataLoading || submitLoading}>
                    <Form className={styles.formWrap} style={{ marginBottom: 100 }}>
                        <Form.Item label="配置名称">
                            {isForm
                                ? form.getFieldDecorator('configName', {
                                    initialValue: data?.configName || undefined,
                                    rules: [
                                        {
                                            required: true,
                                            message: '配置名称不能为空'
                                        }
                                    ]
                                })(<Input placeholder="请输入" allowClear maxLength={200} style={{ width: 528 }} />)
                                : getItem(data?.configName)}
                        </Form.Item>
                        <Form.Item label="适用行政机构">
                            {data?.hasDefault && '全集团'}
                            {!isForm && !data?.hasDefault && getItem(data?.companyName)}
                            {isForm && (
                                <>
                                    {data?.hasDefault &&
                                    form.getFieldDecorator('companyCode', {
                                        initialValue: data?.companyCode || undefined
                                    })(<input type="hidden" />)}
                                    {!data?.hasDefault &&
                                    form.getFieldDecorator('companyCode', {
                                        initialValue:
                                            data?.companyCode || administrativeOrganizationCode || undefined,
                                        rules: [
                                            {
                                                required: true,
                                                message: '适用行政机构不能为空'
                                            }
                                        ]
                                    })(
                                        <OrganizationSelect
                                            style={{ width: 528 }}
                                            isNeedPermission={false}
                                            onlyCompany
                                            placeholder="请选择"
                                            onChange={handleAdministrativeScopeChange}
                                        />
                                    )}
                                </>
                            )}
                        </Form.Item>
                        <Form.Item label="配置内容" style={{ marginBottom: 0 }}>
                            <p>
                                若流程处理人岗位当前无员工在职，系统将逐级向上寻找该岗位的上级处理相关流程
                            </p>
                            <HandoverTable
                                isDrag={isForm}
                                hintMessage="工作交接为首个流程，不可调整至此位置"
                                columns={columns}
                                dataSource={handoverFlowDataSource}
                                setDataSource={setHandoverFlowDataSource}
                                loading={dealDutyLoading}
                            />

                            <div style={{ display: 'flex', marginTop: 10, lineHeight: '40px' }}>
                                <div style={{ whiteSpace: 'nowrap' }}>
                                    离职审批通过后，交接流程及对应的处理人，自动通知关键人事岗位：
                                </div>
                                <Spin spinning={dealDutyLoading} wrapperClassName={styles.spinWrap}>
                                    {isForm
                                        ? <Form.Item>{
                                            form.getFieldDecorator('notifyDutyCodeList', {
                                                initialValue: data?.notifyDutyCodeList || [],
                                                rules: [
                                                    {
                                                        required: true,
                                                        message: '通知关键人不能为空'
                                                    }
                                                ]
                                                // getValueFromEvent
                                            })(<TreeSelect
                                                showArrow
                                                allowClear
                                                showSearch
                                                multiple
                                                placeholder="请选择"
                                                dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                                treeDefaultExpandAll
                                                treeNodeFilterProp="title"
                                                dropdownClassName={styles.treeItemHasDisabledStyle}
                                            >
                                                {generateTreeNodes(dealDutyData || [])}
                                            </TreeSelect>)
                                        }</Form.Item>
                                        : getItem(data?.notifyDutyNameList)}
                                </Spin>
                            </div>
                        </Form.Item>
                        <Form.Item label="人事交接内容">
                            {isForm
                                ? personnelContent.map(box =>
                                    form.getFieldDecorator(`personnel.${box.key}`, {
                                        valuePropName: 'checked',
                                        initialValue: box.initialValue || false
                                    })(<Checkbox disabled={box.disabled}>{box.label}</Checkbox>)
                                )
                                : getShowName(data?.hrHandoverTypes, personnelContent)}
                        </Form.Item>
                        {
                            (!!form.getFieldValue('personnel.salaryResult') || data?.hrHandoverTypes?.includes(4)) && <Form.Item label="薪资结算时间">
                                {isForm
                                    ? form.getFieldDecorator('allowChoiceSalarySettlementTimeFlag', {
                                        initialValue: data?.allowChoiceSalarySettlementTimeFlag
                                            || defaultFlowData?.allowChoiceSalarySettlementTimeFlag
                                            || 1
                                    })(
                                        <Radio.Group>
                                            {SALARY_TIME.map(unit => (
                                                <Radio value={unit.key} key={unit.key}>
                                                    {unit.label}
                                                </Radio>
                                            ))}
                                        </Radio.Group>
                                    )
                                    : SALARY_TIME.find(v => v.key === data?.allowChoiceSalarySettlementTimeFlag)?.label}
                            </Form.Item>
                        }
                        <Form.Item label="财务清算内容">
                            {isForm
                                ? financeContent.map(box => (
                                    <div>
                                        {form.getFieldDecorator(`finance.${box.key}`, {
                                            valuePropName: 'checked',
                                            initialValue: box.initialValue || false
                                        })(<Checkbox disabled={box.disabled}>{box.label}</Checkbox>)}
                                    </div>
                                ))
                                : getShowName(data?.financialSettlementType, financeContent)}
                        </Form.Item>
                    </Form>
                </Spin>
            </Card>
        </PageHeaderWrapper>
    );
};

export default memo(Form.create()(HandoverFlowSettingEdit));
